package fi.foyt.cs.persistence.dao.items;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import fi.foyt.cs.persistence.dao.GenericDAO;
import fi.foyt.cs.persistence.domainmodel.items.Inventory;

public class InventoryDAO extends GenericDAO<Inventory> {

  public Inventory create(Long userId, Double money) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      Inventory inventory = new Inventory();
      inventory.setMoney(money);
      inventory.setUserId(userId);
      entityManager.persist(inventory);
      entityManager.getTransaction().commit();
      return inventory;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
  
  public Inventory updateMoney(Inventory inventory, Double money) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      inventory.setMoney(money);
      inventory = entityManager.merge(inventory);
      entityManager.getTransaction().commit();
      
      return inventory;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
  
  public Inventory findByUserId(Long userId) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from Inventory o where userId = :userId");
    query.setParameter("userId", userId);
    return getSingleResult(query);
  }
}
